import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { 
  User, 
  Mail, 
  Calendar, 
  Settings, 
  Shield, 
  Camera,
  Save,
  Edit,
  BarChart3,
  TrendingUp,
  Award,
  LogOut
} from 'lucide-react';
import { userApi } from '@/services/api';
import { useAuth } from '@/contexts/auth-context';
import { useToast } from '@/hooks/use-toast';

export function ProfilePage() {
  const { user, updateUser, logout } = useAuth();
  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [userInfo, setUserInfo] = useState({
    userName: user?.userName || '',
    userAvatar: user?.userAvatar || '/placeholder.svg?height=100&width=100',
    userProfile: user?.userProfile || '',
  });
  const { toast } = useToast();

  const handleSave = async () => {
    setLoading(true);
    try {
      const response = await userApi.updateMyUser({
        userName: userInfo.userName,
        userAvatar: userInfo.userAvatar,
        userProfile: userInfo.userProfile,
      });
      
      if (response.code === 0) {
        // 更新本地用户信息
        updateUser({
          userName: userInfo.userName,
          userAvatar: userInfo.userAvatar,
          userProfile: userInfo.userProfile,
        });
        
        toast({
          title: "保存成功",
          description: "个人信息已更新",
        });
        setIsEditing(false);
      } else {
        throw new Error(response.message);
      }
    } catch (error: any) {
      toast({
        title: "保存失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const getRoleBadge = (role: string) => {
    switch (role) {
      case 'admin':
        return <Badge className="bg-red-100 text-red-800 hover:bg-red-100">管理员</Badge>;
      case 'vip':
        return <Badge className="bg-yellow-100 text-yellow-800 hover:bg-yellow-100">VIP用户</Badge>;
      default:
        return <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-100">普通用户</Badge>;
    }
  };

  if (!user) {
    return <div>用户信息加载中...</div>;
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center space-x-3">
        <User className="h-8 w-8 text-blue-600" />
        <div>
          <h1 className="text-3xl font-bold text-gray-900">个人中心</h1>
          <p className="text-gray-600">管理您的个人信息和账户设置</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：个人信息 */}
        <div className="lg:col-span-2 space-y-6">
          {/* 基本信息卡片 */}
          <Card className="shadow-lg border-0 bg-white">
            <CardHeader className="bg-gradient-to-r from-blue-50 to-cyan-50 border-b">
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center space-x-2">
                  <Settings className="h-5 w-5 text-blue-600" />
                  <span>基本信息</span>
                </CardTitle>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setIsEditing(!isEditing)}
                >
                  <Edit className="h-4 w-4 mr-2" />
                  {isEditing ? '取消编辑' : '编辑信息'}
                </Button>
              </div>
            </CardHeader>
            <CardContent className="p-6 space-y-6">
              {/* 头像 */}
              <div className="flex items-center space-x-4">
                <div className="relative">
                  <Avatar className="h-20 w-20">
                    <AvatarImage src={userInfo.userAvatar} alt="用户头像" />
                    <AvatarFallback className="text-lg">
                      {userInfo.userName?.charAt(0) || user.userAccount?.charAt(0) || 'U'}
                    </AvatarFallback>
                  </Avatar>
                  {isEditing && (
                    <Button
                      size="sm"
                      variant="outline"
                      className="absolute -bottom-2 -right-2 h-8 w-8 rounded-full p-0"
                    >
                      <Camera className="h-4 w-4" />
                    </Button>
                  )}
                </div>
                <div>
                  <h3 className="text-xl font-semibold text-gray-900">
                    {userInfo.userName || user.userAccount}
                  </h3>
                  <p className="text-gray-600">@{user.userAccount}</p>
                  <div className="mt-2">{getRoleBadge(user.userRole)}</div>
                </div>
              </div>

              {/* 表单字段 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="userName" className="text-sm font-medium text-gray-700">
                    用户名
                  </Label>
                  <Input
                    id="userName"
                    value={userInfo.userName}
                    onChange={(e) => setUserInfo({ ...userInfo, userName: e.target.value })}
                    disabled={!isEditing}
                    placeholder="请输入用户名"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="userAccount" className="text-sm font-medium text-gray-700">
                    账户名
                  </Label>
                  <Input
                    id="userAccount"
                    value={user.userAccount}
                    disabled
                    className="bg-gray-50"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="userProfile" className="text-sm font-medium text-gray-700">
                  个人简介
                </Label>
                <Textarea
                  id="userProfile"
                  value={userInfo.userProfile}
                  onChange={(e) => setUserInfo({ ...userInfo, userProfile: e.target.value })}
                  disabled={!isEditing}
                  className="min-h-[100px] resize-none"
                  placeholder="介绍一下自己..."
                />
              </div>

              {isEditing && (
                <div className="flex space-x-3 pt-4">
                  <Button 
                    onClick={handleSave} 
                    disabled={loading}
                    className="bg-blue-600 hover:bg-blue-700"
                  >
                    <Save className="h-4 w-4 mr-2" />
                    {loading ? '保存中...' : '保存更改'}
                  </Button>
                  <Button 
                    variant="outline" 
                    onClick={() => setIsEditing(false)}
                  >
                    取消
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 账户信息 */}
          <Card className="shadow-lg border-0 bg-white">
            <CardHeader className="bg-gradient-to-r from-green-50 to-emerald-50 border-b">
              <CardTitle className="flex items-center space-x-2">
                <Shield className="h-5 w-5 text-green-600" />
                <span>账户信息</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="flex items-center space-x-3">
                  <div className="p-2 bg-blue-100 rounded-lg">
                    <Mail className="h-4 w-4 text-blue-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600">账户ID</p>
                    <p className="font-medium text-gray-900">{user.id}</p>
                  </div>
                </div>

                <div className="flex items-center space-x-3">
                  <div className="p-2 bg-green-100 rounded-lg">
                    <Calendar className="h-4 w-4 text-green-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600">注册时间</p>
                    <p className="font-medium text-gray-900">{user.createTime}</p>
                  </div>
                </div>

                <div className="flex items-center space-x-3">
                  <div className="p-2 bg-purple-100 rounded-lg">
                    <Settings className="h-4 w-4 text-purple-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600">最后更新</p>
                    <p className="font-medium text-gray-900">{user.updateTime}</p>
                  </div>
                </div>

                <div className="flex items-center space-x-3">
                  <div className="p-2 bg-yellow-100 rounded-lg">
                    <Shield className="h-4 w-4 text-yellow-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray-600">用户角色</p>
                    <p className="font-medium text-gray-900">
                      {user.userRole === 'admin' ? '管理员' : '普通用户'}
                    </p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 右侧：统计信息 */}
        <div className="space-y-6">
          {/* 使用统计 */}
          <Card className="shadow-lg border-0 bg-white">
            <CardHeader className="bg-gradient-to-r from-purple-50 to-pink-50 border-b">
              <CardTitle className="flex items-center space-x-2">
                <BarChart3 className="h-5 w-5 text-purple-600" />
                <span>使用统计</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <TrendingUp className="h-4 w-4 text-blue-600" />
                  <span className="text-sm text-gray-600">创建图表</span>
                </div>
                <span className="text-lg font-semibold text-gray-900">24</span>
              </div>

              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <BarChart3 className="h-4 w-4 text-green-600" />
                  <span className="text-sm text-gray-600">成功分析</span>
                </div>
                <span className="text-lg font-semibold text-gray-900">20</span>
              </div>

              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <Calendar className="h-4 w-4 text-purple-600" />
                  <span className="text-sm text-gray-600">本月使用</span>
                </div>
                <span className="text-lg font-semibold text-gray-900">8</span>
              </div>

              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <Award className="h-4 w-4 text-yellow-600" />
                  <span className="text-sm text-gray-600">使用天数</span>
                </div>
                <span className="text-lg font-semibold text-gray-900">15</span>
              </div>
            </CardContent>
          </Card>

          {/* 快速操作 */}
          <Card className="shadow-lg border-0 bg-white">
            <CardHeader className="bg-gradient-to-r from-orange-50 to-red-50 border-b">
              <CardTitle>快速操作</CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-3">
              <Button variant="outline" className="w-full justify-start">
                <Settings className="h-4 w-4 mr-2" />
                账户设置
              </Button>
              <Button variant="outline" className="w-full justify-start">
                <Shield className="h-4 w-4 mr-2" />
                安全设置
              </Button>
              <Button variant="outline" className="w-full justify-start">
                <Mail className="h-4 w-4 mr-2" />
                通知设置
              </Button>
              <Button 
                variant="outline" 
                className="w-full justify-start text-red-600 hover:text-red-700 hover:bg-red-50"
                onClick={logout}
              >
                <LogOut className="h-4 w-4 mr-2" />
                退出登录
              </Button>
            </CardContent>
          </Card>

          {/* 成就徽章 */}
          <Card className="shadow-lg border-0 bg-white">
            <CardHeader className="bg-gradient-to-r from-yellow-50 to-orange-50 border-b">
              <CardTitle className="flex items-center space-x-2">
                <Award className="h-5 w-5 text-yellow-600" />
                <span>成就徽章</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="p-6">
              <div className="grid grid-cols-2 gap-3">
                <div className="text-center p-3 bg-blue-50 rounded-lg">
                  <BarChart3 className="h-6 w-6 text-blue-600 mx-auto mb-1" />
                  <p className="text-xs text-gray-600">分析师</p>
                </div>
                <div className="text-center p-3 bg-green-50 rounded-lg">
                  <TrendingUp className="h-6 w-6 text-green-600 mx-auto mb-1" />
                  <p className="text-xs text-gray-600">数据专家</p>
                </div>
                <div className="text-center p-3 bg-purple-50 rounded-lg">
                  <Award className="h-6 w-6 text-purple-600 mx-auto mb-1" />
                  <p className="text-xs text-gray-600">活跃用户</p>
                </div>
                <div className="text-center p-3 bg-yellow-50 rounded-lg">
                  <Calendar className="h-6 w-6 text-yellow-600 mx-auto mb-1" />
                  <p className="text-xs text-gray-600">早期用户</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}